<?php

class Mobileservice_LoginController extends Core_Controller_Action_Standard
{
  public function indexAction()
  {
	$this->_helper->layout->disableLayout();
    $this->_helper->viewRenderer->setNoRender();
	$email=$_POST['email'];
	$password=$_POST['password'];
	$email = str_replace(' ', '', $email);
    $password=str_replace(' ', '', $password);
    

        // Check login creds
    //extract($form->getValues()); // $email, $password, $remember
    $user_table = Engine_Api::_()->getDbtable('users', 'user');
    $user_select = $user_table->select()
      ->where('email = ?', (string)$email);          // If post exists
    $user = $user_table->fetchRow($user_select);
    // Get ip address
	
    $db = Engine_Db_Table::getDefaultAdapter();
    $ipObj = new Engine_IP();
    $ipExpr = new Zend_Db_Expr($db->quoteInto('UNHEX(?)', bin2hex($ipObj->toBinary())));
	
    // Check if user exists
    if( empty($user) ) {
      $this->view->status = false;
     // $this->view->error = Zend_Registry::get('Zend_Translate')->_('No record of a member with that email was found.');
   // echo 'No record of a member with that email was found.';
	//echo json_encode(array('result'=>'No User:-' .'vomtung'. '-found'));
	echo json_encode(array('result'=>'No User:-' .$email. '-found'));
      // Register login
	  
      Engine_Api::_()->getDbtable('logins', 'user')->insert(array(
        'email' => $email,
        'ip' => $ipExpr,
        'timestamp' => new Zend_Db_Expr('NOW()'),
        'state' => 'no-member',
      ));
		
      return;
    }
	

     

      $authResult = Engine_Api::_()->user()->authenticate($email, $password);
      $authCode = $authResult->getCode();
	
      if( $authCode != Zend_Auth_Result::SUCCESS ) {
        $this->view->status = false;
        $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid credentials');
		echo json_encode(array("result"=>"Invalid User Name or Password"));
        
        // Register login
        Engine_Api::_()->getDbtable('logins', 'user')->insert(array(
          'user_id' => $user->getIdentity(),
          'email' => $email,
          'ip' => $ipExpr,
          'timestamp' => new Zend_Db_Expr('NOW()'),
          'state' => 'bad-password',
        ));

        return;
      }
	 
	

    // -- Success! --

    // Register login
    $loginTable = Engine_Api::_()->getDbtable('logins', 'user');
    $loginTable->insert(array(
      'user_id' => $user->getIdentity(),
      'email' => $email,
      'ip' => $ipExpr,
      'timestamp' => new Zend_Db_Expr('NOW()'),
      'state' => 'success',
      'active' => true,
    ));
    $_SESSION['login_id'] = $login_id = $loginTable->getAdapter()->lastInsertId();
    
    // Remember
    if( $remember ) {
      $lifetime = 1209600; // Two weeks
      Zend_Session::getSaveHandler()->setLifetime($lifetime, true);
      Zend_Session::rememberMe($lifetime);
    }

    // Increment sign-in count
    Engine_Api::_()->getDbtable('statistics', 'core')
        ->increment('user.logins');

    // Test activity @todo remove
    $viewer = Engine_Api::_()->user()->getViewer();
    if( $viewer->getIdentity() ) {
      $viewer->lastlogin_date = date("Y-m-d H:i:s");
      if( 'cli' !== PHP_SAPI ) {
        $viewer->lastlogin_ip = $ipExpr;
      }
      $viewer->save();
      Engine_Api::_()->getDbtable('actions', 'activity')
          ->addActivity($viewer, $viewer, 'login');
    }

    // Assign sid to view for json context
    $this->view->status = true;
    //echo 'Login successful';
	echo json_encode(array("result"=>"Successful"));


  }
}
